package com.tsxy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tsxy.entity.Menu;
import com.tsxy.entity.Role;
import com.tsxy.entity.RoleMenu;
import com.tsxy.mapper.RoleMapper;
import com.tsxy.mapper.RoleMenuMapper;
import com.tsxy.service.IMenuService;
import com.tsxy.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AutoPopulatingList;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 飞
 * @since 2022-02-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private IMenuService MenuService;

    @Override
    @Transactional
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        /*QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        roleMenuMapper.delete(queryWrapper);*/
        //先删除当前角色id所有的绑定关系
        roleMenuMapper.deleteByRoleId(roleId);
        boolean flag = true;
        for (Integer menuId : menuIds) {
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", menuId);
            Menu menu = MenuService.getOne(queryWrapper);
            if (flag && menu.getPid() != null && ! menuIds.contains(menu.getPid())){
                roleMenuMapper.insert(new RoleMenu(roleId,menu.getPid()));
                flag = false;
            }
        }
        //添加现在的绑定的关系
        roleMenuMapper.insertAll(roleId,menuIds);
    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        List<Integer> roleMenu = roleMenuMapper.getByRoleId(roleId);
        /*List<Menu> menus = MenuService.getAll().stream().filter(menu -> menu.getChildren() != null).collect(Collectors.toList());*/
        List<Menu> menus = MenuService.getAll();
        List<Integer> ids = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getChildren().size() != 0 ){
                ids.add(menu.getId());
            }
        }
        List<Integer> iter = CollUtil.newArrayList(roleMenu);
        for (Integer role : iter) {
            if (ids.contains(role) ){
                roleMenu.remove(role);
            }
        }
        return roleMenu;
    }
}
